﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Script.Serialization;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public partial class UnitControler : System.Web.UI.Page
{
    MyDbHelper mydb = new MyDbHelper();
    sendweixin weixin = new sendweixin();
    protected void Page_Load(object sender, EventArgs e)
    {
        string aciton = Request.Params["aciton"];
        switch (aciton)
        {
            case "lodshoplist":
                lodshoplist();
                break;
            case "getwxopenid":
                getwxopenid();
                break;
            case "updwxopenid":
                updwxopenid();
                break;
            case "updwxpaynum":
                updwxpaynum();
                break;
            case "insetlogs":
                insetlogs();
                break;
            case "checkstock":
                checkstock();
                break;
            case "saveorder":
                saveorder();
                break;
            case "getwxconfig":
                getwxconfig();
                break;
        }
    }



    private void getwxconfig()
    {
        object result = null;
        string timestamp = getTimestamp(); // 必填，生成签名的时间戳
        string nonceStr = getNoncestr();  // 必填，生成签名的随机串
        string signature = Getsignature(nonceStr, timestamp);// 必填，签名，见附录1
        if (signature != "")
        {
            result = new { status = 0, appid = "wx6d3a3a25e9576db6", timestamp = timestamp, nonceStr = nonceStr, signature = signature };
        }
        else
        {
            result = new { status = -1, msg = "出现错误" };
        }
        Response.Write(JsonHelper.SerializeObject(result));
        Response.End();
    }

    /// <summary>
    /// 生成时间戳
    /// 从 1970 年 1 月 1 日 00：00：00 至今的秒数，即当前的时间，且最终需要转换为字符串形式
    /// </summary>
    /// <returns></returns>
    public string getTimestamp()
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds).ToString();
    }
    /// <summary>
    /// 生成随机字符串
    /// </summary>
    /// <returns></returns>
    public string getNoncestr()
    {
        Random random = new Random();
        return MD5Util.GetMD5(random.Next(1000).ToString(), "GBK");
    }
    public string Getsignature(string nonceStr, string timespanstr)
    {
        string ticketzj = weixin.getjstoken();
        //string url = Request.Url.ToString();

        string str = "jsapi_ticket=" + ticketzj + "&noncestr=" + nonceStr +
            "&timestamp=" + timespanstr + "&url=https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6d3a3a25e9576db6&redirect_uri=http%3A%2F%2Fweixin.km-china.cn%2Fkmwx%2Flottery.html&response_type=code&scope=snsapi_base&state=123#wechat_redirect";// +"&wxref=mp.weixin.qq.com";
        string singature = SHA1Util.getSha1(str);
        string ss = singature;
        return ss;
    }
    private void saveorder()
    {
        string openid=Request.Params["openid"];
        string pid = Request.Params["pid"];
        string username = Request.Params["username"];
        string phone = Request.Params["phone"];
        string bigarea = Request.Params["bigarea"];
        string city = Request.Params["city"];
        string address = Request.Params["address"];
        string sql = "insert into Bas_WxOrders values('" + openid + "'," + pid + ",'" + username + "','" 
            + phone + "','" + bigarea + "','" + city + "','" + address + "',getdate())";
        object result = null;
        if (mydb.DM_ExecuteNonQuery(sql) != -1)
        {
            result = new { status = 0, msg = "操作成功" };
        }
        else
        {
            result = new { status = -1, msg = "出现错误" };
        }
        Response.Write(JsonHelper.SerializeObject(result));
        Response.End();
    }

    private void checkstock()
    {
        object result = null;
        string pid = Request.Params["pid"];
        try
        {
            int qty = Convert.ToInt32(mydb.DM_GetExecuteScalarObj("select qty from Bas_prize where pid =" + pid).ToString());
            if (qty > 0)
            {
                if (mydb.DM_ExecuteNonQuery("update Bas_prize set qty=qty-1 where pid=" + pid) != -1)
                {
                    result = new { status = 0, msg = "操作成功" };
                }
                else
                {
                    result = new { status = -1, msg = "出现错误" };
                }
            }
            else
            {
                result = new { status = 1, msg = "库存不足" };
            }
        }
        catch (Exception ex)
        {
            result = new { status = -1, msg = ex.Message };
        }
        Response.Write(JsonHelper.SerializeObject(result));
        Response.End();
    }
    private void insetlogs()
    {
       object result = null;
        string sql = "";
        string openid = Request.Params["openid"];
        string pid = Request.Params["pid"];
        if (openid != "")
        {
            if (pid != "5")//'再来一次不作记录
            {
                sql = " insert into Bas_LotteryRecord values('" + openid + "'," + pid + ",getdate()) ";
            }
            sql += " insert into Bas_LotteryRecord2 values('" + openid + "'," + pid + ",getdate()) ";
            if (mydb.DM_ExecuteNonQuery(sql) != -1)
            {
                result = new { status = 0, msg = "操作成功" };
            }
            else
            {
                result = new { status = -1, msg = "出现错误" };
            }
        }
        else
        {
            result = new { status = -1, msg = "出现错误" };
        }
        Response.Write(JsonHelper.SerializeObject(result));
        Response.End();
    }
    private void updwxpaynum()
    {
        object result = null;
        string sql = "";
        string openid = Request.Params["openid"];
        sql = "update Bas_WeixinUser set paynum = 0 where openid='" + openid + "'";
        if (mydb.DM_ExecuteNonQuery(sql) != -1)
        {
            result = new { status = 0, msg = "操作成功" };
        }
        else
        {
            result = new { status = -1, msg = "出现错误" };
        }
        Response.Write(JsonHelper.SerializeObject(result));
        Response.End();
    }

    private void updwxopenid()
    {
        object result = null;
        string sql = "";
        string openid = Request.Params["openid"];
        string pid = Request.Params["pid"];
        if (openid !="")
        {
           //sql = "select * from Bas_WeixinUser where openid='"+openid+"' and isnull(paynum,0)>0";
            //每天可以抽3次奖。
            sql = "select * from Bas_LotteryRecord where openid='" + openid + "' and convert(varchar(20),createdate,23) = '"
                + DateTime.Now.ToString("yyyy-MM-dd") + "'";
            DataSet ds  = mydb.DM_GetDateSet(sql);
            if (ds != null)
            {
                //pid = 5 再来一次
                if (ds.Tables[0].Rows.Count >= 3 && pid != "5")
                {
                    result = new { status = 1, msg = "对不起，您今天已经没有抽奖机会！" };
                }
                else
                {
                    result = new { status = 0, msg = "操作成功" };
                }
            }
            else
            {
                result = new { status = -1, msg = openid + "出现错误" };
            }
        }
        else
        {
            result = new { status = -1, msg = openid+"出现错误" };
        }
        Response.Write(JsonHelper.SerializeObject(result));
        Response.End();
    }

    private void getwxopenid()
    {
        object result = null;
        string sql = "";
        string code = Request.Params["code"];
        string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx6d3a3a25e9576db6&secret=3a444c2ec6dc28963fc6a20037a560cf&code=" + code + "&grant_type=authorization_code";
        string acctoken = weixin.GetModel(url);
        if (acctoken != null && acctoken.Trim() != "")
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            JsonObject_token jstk = serializer.Deserialize<JsonObject_token>(acctoken);
            if (jstk.openid !=null && jstk.openid.Trim() != "")
            {
                if (mydb.DM_GetDateSet("select *from Bas_WeixinUser where openid='" + jstk.openid + "'").Tables[0].Rows.Count > 0)
                {
                    result = new { status = 1, msg = "操作成功", openid = jstk.openid };
                }
                else
                {
                    sql = "insert into Bas_WeixinUser(openid,paynum,CreateDate)values('" + jstk.openid + "',0,getdate())";
                    if (mydb.DM_ExecuteNonQuery(sql) != -1)
                    {
                        result = new { status = 0, msg = "操作成功", openid = jstk.openid };
                    }
                    else
                    {
                        result = new { status = -1, msg = "出现错误" };

                    }
                }
            }
            else
            {
                result = new { status = -1, msg = "openid出现错误" };
            }

            Response.Write(JsonHelper.SerializeObject(result));
            Response.End();
        }
    }
    private void lodshoplist()
    {
        string shopname = Request.Params["shopname"];
        string str = "";
        if (shopname != "")
        {
            str += " and shopname like '%" + shopname + "%'";
        }
        DataSet ds = mydb.DM_GetDateSet(@"select shopid,shopname from v_shoplist where 1=1 " + str + " order by shopid");
        if (ds.Tables[0].Rows.Count > 0)
        {
            string sbr = "";
            sbr = "[";
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                sbr += "{\"shopname\":\"" + dr["shopname"]
                    + "\",\"shopid\":\"" + dr["shopid"]
                    + "\"},";
            }
            sbr = sbr.TrimEnd(',') + "]";
            Response.Write(sbr);
            Response.End();
        }
        else
        {
            Response.Write("NO_DATA");
            Response.End();
        }

    }
}

public class JsonObject_token
{
    public string access_token { get; set; }
    public string expires_in { get; set; }
    public string refresh_token { get; set; }
    public string openid { get; set; }
    public string scope { get; set; }
    
}
class SHA1Util
{
    public static String getSha1(String str)
    {
        //建立SHA1对象
        SHA1 sha = new SHA1CryptoServiceProvider();
        //将mystr转换成byte[] 
        ASCIIEncoding enc = new ASCIIEncoding();
        byte[] dataToHash = enc.GetBytes(str);
        //Hash运算
        byte[] dataHashed = sha.ComputeHash(dataToHash);
        //将运算结果转换成string
        string hash = BitConverter.ToString(dataHashed).Replace("-", "");
        return hash;
    }
}